<?php
/**
 * 
 *
 * @author 
 * @version v1.0.0
 *
 **/
namespace Xijie\Controller;
use Think\Controller;

class MemberController extends Controller {
	public function __construct() {
        parent::__construct();
		//判断是否登陆
		if(session('user_id')){ //已登陆
			
		}else{ //未登陆，跳转道登陆界面
			$this->redirect("index/index");
		}
    }
	
	/**
	 * 用户列表
	 *
	 **/
	public function lists(){
		$page = I('get.page') ? (int)I('get.page') : 1;
		$ajax = I('get.ajax') ? (int)I('get.ajax') : 0;
		//获取房间号
		$roomnumber = I("get.roomnumber");
		if(!empty($roomnumber)){
			$param['roomnumber'] = $where['member.room_number'] = $roomnumber;
		}
		
		$nickname = I("get.nick", "");
		if(!empty($nickname)){
			$param['nick'] = $nickname;
			$where['member_nick'] = array('like', '%'. $nickname . '%');
		}
		//合同号
		$contract = I('get.contract', '');
		if(!empty($contract)){
			$param['contract'] = $contract;
			$where['member.contract'] = array('like','%'. $contract .'%');
		}
		
		//会员状态
		$param['visible'] = $status = I('get.visible', 'all');
		if($status !== 'all'){
			if($status == 1){
				$where['member.visible'] = 1;
			}else if($status == 2){
				$where['member.visible'] = 0;
			}else if($status == 3){
				$where['member.visible'] = -1;
			}
			//$where['member.visible'] = $status == 2 ? 0 : 1;
		}
		
		//开始时间与结束时间
		$param['btime'] = $btime = I('get.btime', 0);
		$param['etime'] = $etime = I('get.etime', 0);
		if(!empty($btime) && empty($etime)){
			$where['btime'] = array('egt', strtotime($btime . ' 00:00:00'));
		}

		if(empty($btime) && !empty($etime)){
			$where['btime'] = array('elt', strtotime($etime . ' 23:59:59'));
		}

		if(!empty($btime) && !empty($etime)){
			$where['btime'] = array('between', array(
				strtotime($btime .' 00:00:00'),
				strtotime($etime .' 23:59:59')
			));
		}

		//合同总数
		$count = D('Member')->getMemberListCount($where);
		//在租总数
		$online = D('Member')->getMemberListCount(array(
			'member.visible' => 1
		));
		//昨日新增
		$yearsdattime = date('Y-m-d', strtotime("-1 day"));
		$yearsday = D('Member')->getMemberListCount(array(
			'member.btime' => array('between', array(
				strtotime($yearsdattime. ' 00:00:00'), 
				strtotime($yearsdattime .' 23:59:59'))
			),
			'member.visible' => 1
		));
		//今日新增
		$todaytime = date('Y-m-d');
		$todayday = D('Member')->getMemberListCount(array(
			'member.btime' => array('between', array(
					strtotime($todaytime. ' 00:00:00'), 
					strtotime($todaytime .' 23:59:59'))
			),
			'member.visible' => 1
		));
		//用户列表
		$userlist = D('Member')->getMemberList($page, $where);
		
		$this->assign('userlist', $userlist);
		$this->assign('count', $count);
		$this->assign('online', $online);
		$this->assign('yearsday', $yearsday);
		$this->assign('todayday', $todayday);
		$this->assign('page', $page);

		if(is_array($param)){
			$this->assign('param', json_encode($param));
		}
		//判断请求方式
		if(!$ajax){
			$this->display('lists');
		}else{
			$this->display('list_table', 'utf-8', 'html');
		}
	}
	
	/**
	 * 续约提醒
	 *
	 **/
	public function renew(){
		if(IS_GET){
			$page = I('get.page') ? (int)I('get.page') : 1;
			$ajax = I('get.ajax') ? (int)I('get.ajax') : 0;
			//获取查询时间
			$bdays = date('Y-m-d', strtotime("-1 day"));
			$btime = I('get.btime', $bdays);
			$etime = I('get.etime', date('Y-m-d', time()));
			
			$param['btime'] = $btime;
			$param['etime'] = $etime;
			//设置查询条件
			//$where["to_days(FROM_UNIXTIME(member.etime, '%Y%m%d')) - to_days(now())"] = array('eq', $days);
			//按时间端查询到期数据
			$where['member.etime'] = array('between',array(strtotime($btime. ' 00:00:00'),strtotime($etime. ' 23:59:59')));
			$where['member.visible'] = 1;
			//总数
			$count = D('Member')->getMemberListCount($where);
			//用户列表
			$userlist = D('Member')->getMemberList($page, $where, 'member.etime asc');
			
			$this->assign('userlist', $userlist);
			$this->assign('count', $count);
			$this->assign('page', $page);
			$this->assign('btime', $btime);
			$this->assign('etime', $etime);
			$this->assign('param', json_encode($param));
			//判断请求方式
			if(!$ajax){
				$this->display('renew');
			}else{
				$this->display('renew_list', 'utf-8', 'html');
			}
		}else{ //邀约
			$userid = I('post.userid', 0);
			$userinfo = D('Member')->getMemberInfoById($userid);
			$type = I('type', 0);
			$rewresult = I('post.rewresult', 0);
			if($userinfo){
				if($type){
					$row = D('Member')->editMemberInfo($userid, array(
						'rewresult' => $rewresult
					));
				}else{
					$flag = sendSMSMessage($userinfo['member_phone'], '', $userinfo['member_nick'], '',$userinfo['room_number'], date('Y-m-d', $userinfo['etime']), 2);
					if($flag){
						$row = D('Member')->editMemberInfo($userid, array(
							'rewentime' => time(),
							'rewencount' => array('exp', 'rewencount + 1')
						));
						//添加操作日志
						M('admin_log')->data(array(
							'type' => 1,
							'log_id' => $userid,
							'createtime' => time(),
							'admin_nick' => session('nickname')
						))->add();
					}
				}
				
				if($row !== false){
					echo 1;
				}else{
					echo 0;
				}
			}else{
				echo 0;
			}
		}
	}

	/**
	 * 导出用户数据为Excel格式
	 *
	 ***/
	public function excel(){
		$list = D('Member')->getMemberListAll();
		$xlsCell = array(
			array('member_nick', '客人姓名'),
			array('member_card','身份证'),
			array('member_phone','联系方式'),
			array('room_number','房间号'),
			array('visible','状态'),
			array('code','验证码'),
			array('checkin_time','入住时间'),
			array('leaving_time','退房时间'),
			array('nickname','操作员'),
			array('createtime','添加时间'),
		);
		if(is_array($list)){
			foreach($list as $ls){
				$excelData[] = array(
					'member_nick' => $ls['member_nick'],
					'member_card' => $ls['member_card'],
					'member_phone' => $ls['member_phone'],
					'room_number' => $ls['room_number'],
					'visible' => $ls['visible'] == 1 ? '租用中' : '无效',
					'code' => $ls['code'],
					'checkin_time' => date('Y-m-d H:i', $ls['checkin_time']),
					'leaving_time' => date('Y-m-d H:i', $ls['leaving_time']),
					'nickname' => $ls['nickname'],
					'createtime' => date('Y-m-d H:i', $ls['createtime'])
				);
			}
		}
		//执行
		D('Excel')->exportExcel('客人信息表', $xlsCell, $excelData, '客人信息表_'.date('Y-m-d H:i'));			
	}
	
	/**
	 * 删除客人
	 **/
	public function remove(){
		if(IS_POST){
			$user_id = I('user_id');
			$state = I('post.status') ? (int)I('post.status') : 0;
			$type = I('post.type', 0);

			if($user_id <= 0 ){
				$this->ajaxReturn(0, 'json');
			}else{
				//获取用户基本信息
				$memberinfo = D('Member')->getMemberInfoById($user_id, 0);
				if(count($memberinfo)){
					if($memberinfo['visible'] == -1){ //未激活状态
						if(($memberinfo['btime'] - time()) > 86400 && $state == 1){ //提前一天
							$this->ajaxReturn(2, 'json');
							exit;
						}
					}
					
					if($type){
						$row = D('Member')->reviewMemberInfo($user_id, $state);
					}else{
						$row = D('Member')->delMemberInfo($user_id, $state);
					}

					if($row !== false){
						$this->ajaxReturn(1, 'json');
					}else{
						$this->ajaxReturn(0, 'json');
					}
				}else{
					$this->ajaxReturn(0, 'json');
				}
			}
		}
	}
	
	/**
	 * 添加编辑客人信息
	 *
	 **/
	public function add(){
		if(IS_GET){
			$member_id = I('get.member_id') ? (int)I('get.member_id') : 0;
			if($member_id){
				$info = D('Member')->getMemberInfoById($member_id, 0);
				//获取房间类型
				$roomInfo = D('Room')->getRoomInfoByNumber($info['room_number']);
				//加载活动
				$event = D('Eventtype')->getMemberEventTypeByBtime(date('Y-m-d', $info['btime']), date('Y-m-d', $info['etime']), $roomInfo['root_type'], $info['contract']);
				//返回值
				$this->assign('event', $event);
				/*
				//获取水电起数
				$eqmlist = D('Eqment')->getEqmentListByRoomnumber($info['room_number']);
				if(is_array($eqmlist) && count($eqmlist)){
					foreach($eqmlist as $ls){
						$info['eqment_'. $ls['typeid']] = $ls['last_number']/10;
					}
				}*/
				$this->assign('userinfo', $info);
			}
			//获取合同列表
			$contractlist = D('Member')->getContractListByWhere(array(
				'status' => 0,
				'visible' => 1
			), 1, 'contract_id asc');

			$this->assign('contractlist', $contractlist);

			$this->display('add');
		}else if(IS_POST){
			$member_id = I('post.member_id') ? (int)I('post.member_id') : 0;
			$data = array(
				'contract' => I('post.contract') ? trim(I('post.contract')) : '',
				'member_nick' => I('post.member_nick') ? trim(I('post.member_nick')) : '',
				'member_card' => I('post.member_card') ? trim(I('post.member_card')) : '',
				'room_number' => I('post.room_number') ? trim(I('post.room_number')) : '',
				'member_phone' => I('post.member_phone') ? trim(I('post.member_phone')) : '',
				'j_name' => I('post.j_name', ''),
				'j_phone' => I('post.j_phone', ''),
				'checkin_time' => I('post.checkin_time'),
				'leaving_time' => I('post.leaving_time'),
				'property_time' => I('post.property_time'),
				'deposit' => I('post.deposit') ? I('post.deposit') : 0,
				'btime' => I('post.btime'),
				'etime' => I('post.etime'),
				'address' => I('post.address', '')
			);
			
			$times = '';

			if(empty($data['btime'])){
				$this->ajaxReturn('请选择入住时间', 'json');
				exit;
			}else{
				$times = $data['btime'];
				$data['btime'] = strtotime($data['btime']);
			}
			
			if(empty($data['etime'])){
				$this->ajaxReturn('请选择离开时间', 'json');
				exit;
			}else{
				$times = $times .'~'. $data['etime'];
				$data['etime'] = strtotime($data['etime'].' 00:00:00');
			}

			if($data['etime'] < $data['btime']){
				$this->ajaxReturn('合同结束时间必须大于开始时间', 'json');
				exit;
			}
			$data['checkin_time'] = strtotime($data['checkin_time']);
			$data['leaving_time'] = strtotime($data['leaving_time']);
			$data['property_time'] = strtotime($data['property_time']);
			
			//优惠金额
			$discount = I('post.discount');
			if(!empty($discount)){
				$data['discount'] = $discount;
			}

			//备注
			$remark = I('post.remark');
			if(!empty($remark)){
				$data['remark'] = $remark;
			}

			//判断享受的月租规则
			$roomrent = D('Room')->getRoomRentByGuiZe($data['room_number'], $data['btime']);
			if(!count($roomrent)){
				$roomrent = D('Room')->getRoomInfoByNumber($data['room_number']);
			}

			//设置动态房租与物业费用
			$data['rent'] = $roomrent['rent'];
			$data['property'] = $roomrent['property'];
			$data['deposit'] = $roomrent['deposit'];
			//开始上传图片
			$images = I('post.images', '');
			if(!empty($images)){
				$data['images'] = $images;
			}
			if($member_id){
				//查询用户信息
				$userinfo = D('Member')->getMemberInfoById($member_id, 0);
				if(count($userinfo)){
					$password = I('post.password', '');
					if((date('Y-m-d', $userinfo['checkin_time']) != date('Y-m-d', $data['checkin_time']) 
						|| date('Y-m-d',$userinfo['leaving_time']) != date('Y-m-d', $data['leaving_time'])
						|| date('Y-m-d',$userinfo['property_time']) != date('Y-m-d', $data['property_time'])
						|| date('Y-m-d',$userinfo['btime']) != date('Y-m-d', $data['btime'])
						|| date('Y-m-d',$userinfo['etime']) != date('Y-m-d', $data['etime'])))
					{
						if(empty($password)){
							$this->ajaxReturn('请输入管理员密码', 'json');
						}else{
							$adminInfo = D('Users')->getUserInfoByName('admin');
							if($adminInfo['password'] == md5($password)){
								//
							}else{
								$this->ajaxReturn('管理员密码错误', 'json');
							}
						}
					}
					
					//读取水电气起数
					$data['eqment_1'] = I('post.eqment_1', 0);
					$data['eqment_2'] = I('post.eqment_2', 0);
					$data['eqment_3'] = I('post.eqment_3', 0);
					//编辑数据
					$row = D('Member')->editMemberInfo($member_id, $data);
				}else{
					$this->ajaxReturn('用户不存在', 'json');
				}
			}else{
				//开始判断参数
				if(empty($data['member_nick'])){
					$this->ajaxReturn('请输入客人名字', 'json');
					exit;
				}
				
				if(empty($data['contract'])){
					$this->ajaxReturn('请输入合同编号', 'json');
					exit;
				}
				
				if(empty($data['member_card'])){
					$this->ajaxReturn('请输入客人身份证', 'json');
					exit;
				}
				
				if(empty($data['member_phone'])){
					$this->ajaxReturn('请输入客人联系方式', 'json');
					exit;
				}
				
				if(empty($data['room_number'])){
					$this->ajaxReturn('请输入房间号', 'json');
					exit;
				}
				
				//判断合同编号是否存在
				if(D('Member')->getMemberInfoByContract($data['contract'])){
					$this->ajaxReturn('合同编号已存在', 'json');
					exit;
				}
				//获取房间对应的ID
				$room = D('Room')->getRoomInfoByNumber($data['room_number']);
				if(is_array($room) && count($room)){
					$data['room_id'] = $room['room_id'];
				}else{
					$this->ajaxReturn('不存在该房间', 'json');
				}
				
				//判断该房间下是否存在未停用的用户
				$minfo = D('Member')->getMemberInfoByRoomnumber($data['room_number']);
				
				//这里需要判断是否存在预存用户
				if(count($minfo)){
					//判断当前录入的用户开始时间是否大于未结束用户的结束时间
					if($minfo['etime'] > $data['btime']){ //2017-09-27 将 >= 修改成 >
						$this->ajaxReturn('预定用户租期开始时间必须大于现租用户结束时间。', 'json');
						exit;
					}else{
						//判断是否存在预定用户
						$YuDingList = D('Member')->getYuDingInfoByRoomnumber($data['room_number']);
						$count = count($YuDingList);
						if($count){
							//开始判断合同时间段是否存在预定
							foreach($YuDingList as $ls){
								//1. 如果预定的开始时间大于记录结束时间
								if($data['btime'] >= $ls['etime']){
									$visible = -1;
								}else{
									//2. 开始时间小于记录的结束时间，判断是否小于开始时间
									if($data['btime'] <= $ls['btime'] && $data['etime'] <= $ls['btime']){
										$visible = -1;
									}else{
										$visible = 0;
										break;
									}
								}
							}
							
							if($visible == 0){
								$this->ajaxReturn('该合同时间段已存在预定用户，不能办理新入住信息。', 'json');
								exit;
							}else{
								$data['visible'] = -1;
							}
						}else{
							$data['visible'] = -1;
						}
					}
				}else{
					//判断是否存在预定用户
					$YuDingList = D('Member')->getYuDingInfoByRoomnumber($data['room_number']);
					$count = count($YuDingList);
					if($count){
						//开始判断合同时间段是否存在预定
						foreach($YuDingList as $ls){
							//1. 如果预定的开始时间大于记录结束时间
							if($data['btime'] >= $ls['etime']){
								$visible = 1;
							}else{
								//2. 开始时间小于记录的结束时间，判断是否小于开始时间
								if($data['btime'] <= $ls['btime'] && $data['etime'] <= $ls['btime']){
									$visible = 1;
								}else{
									$visible = 0;
									break;
								}
							}
						}
						
						if($visible == 0){
							$this->ajaxReturn('该合同时间段已存在预定用户，不能办理新入住信息。', 'json');
							exit;
						}else{
							$data['visible'] = 1;
						}
					}else{
						$data['visible'] = 1;
					}
				}
				
				//开始保存数据
				$data['createtime'] = time();
				$data['code'] = rand(100000, 999999);
				$data['user_id'] = session('user_id');
				
				$type = I('post.type') ? trim(I('post.type')) : '';
				if($type == '长租'){
					$data['istype'] = 1;
				}else{
					$data['istype'] = 0;
				}
				
				$floor = I('post.floor') ? (int)I('post.floor') : 1;
				$roomtype = I('post.roomtype') ? trim(I('post.roomtype')) : '';
				
				//关联设备
				$eqmlist = D('Eqment')->getEqmentListByRoomnumber($data['room_number']);
				if(is_array($eqmlist) && count($eqmlist)){
					foreach($eqmlist as $ls){
						$arr = array(
							'eqment_id' => $ls['id'],
							'eqmnumber' => $ls['eqmnumber'],
							'typeid' => $ls['typeid'],
							'eqmtitle' => $ls['eqmtitle'],
							'room_id' => $ls['room_id'],
							'roomnumber' => $ls['roomnumber'],
							'contract' => $data['contract'],
							'real_start_number' => $ls['last_number'],
							'real_last_number' => $ls['last_number'],
							'old_last_number' => $ls['last_number'],
							'rates' => $ls['rates'],
							'user_id' => session('user_id'),
							'user_nick' => session('nickname'),
							'createtime' => time(),
						);
						
						if($ls['typeid'] == 1){
							$eqment_1 = I('post.eqment_1');
							$ls['last_number'] = $data['eqment_1'] = empty($eqment_1) ? $ls['last_number']/10 : (int)$eqment_1;
						}else if($ls['typeid'] == 2){
							$eqment_2 = I('post.eqment_2');
							$ls['last_number'] = $data['eqment_2'] = empty($eqment_2) ? $ls['last_number']/10 : (int)$eqment_2;
						}else if($ls['typeid'] == 3){
							$eqment_3 = I('post.eqment_3');
							$ls['last_number'] = $data['eqment_3'] = empty($eqment_3) ? $ls['last_number']/10 : (int)$eqment_3;
						}
						
						$newAtt[] = $arr;
					}
				}
				
				$data['checkin_time'] = 0;
				$data['leaving_time'] = 0;
				$data['property_time'] = 0;
				//添加用户信息
				$row = D('Member')->addMemberInfo($data);
				//发送短信验证码
				if($row !== false){
					//关联表信息
					D('EqmentRoom')->addEqmentInfoToRoomAll($newAtt);
					//发短信
					$this->sendCode($data['member_phone'], $data['code'], $data['member_nick'], $type, $data['room_number'], $floor, $roomtype, $times);
					//修改合同号状态
					M('contract')->where(array('contract' => $data['contract']))->setField('status', 1);
				}
			}
			
			if($row !== false){
				$this->ajaxReturn('操作成功', 'json');
			}else{
				$this->ajaxReturn('操作失败', 'json');
			}
		}
	}
	
	public function send(){
		$member_id = I('get.user_id') ? (int)I('get.user_id') : 0;
		$info = D('Member')->getMemberInfoById($member_id, 0);
		if(is_array($info) && count($info)){
			$times = date('Y-m-d H:i', $info['checkin_time']) .'~'. date('Y-m-d H:i', $info['leaving_time']);
			$flag = $this->sendCode($info['member_phone'], $info['code'], $info['member_nick'], 1, $info['room_number'],1,'豪华型', $times);
			if($flag){
				$this->ajaxReturn(1);
			}else{
				$this->ajaxReturn(0);
			}
		}
	}
	
	/**
	 * 数据导入
	 **/
	public function import(){
		ini_set('max_execution_time', '0');
		$allowedExts = array("xlsx", "xls");
		$temp = explode(".", $_FILES["file"]["name"]);
		$extension = end($temp);     // 获取文件后缀名
		if (($_FILES["file"]["size"] < 2048000) && in_array($extension, $allowedExts)){
			if ($_FILES["file"]["error"] > 0){
				echo "Error：: " . $_FILES["file"]["error"] . "<br>";
			}else{
				// 如果没有 upload 目录，你需要创建它，upload 目录权限为 777
				move_uploaded_file($_FILES["file"]["tmp_name"], "./Public/excel/" . $_FILES["file"]["name"]);
				$filename = "./Public/excel/". $_FILES["file"]["name"];
				//获取excel数据
				$list = D('Excel')->readExcel($filename, $temp, 2);
				if(is_array($list) && count($list) >= 1){
					foreach($list as $lss){
						if($lss['P'] == '生效'){
							$data = array(
								'contract' => $lss['B'],
								'member_nick' => $lss['C'],
								'member_card' => $lss['H'],
								'room_number' => $lss['E'],
								'member_phone' => $lss['F'],
								'btime' => time(),
								'etime' => strtotime($lss['J']),
								'deposit' => 0
							);
							//判断合同号是否存在
							$count = D('Member')->getMemberListCount(array(
								'contract' => $lss['B']
							));
							//开始添加
							if(!$count){
								//获取房间对应的ID
								$room = D('Room')->getRoomInfoByNumber($data['room_number']);
								if(is_array($room) && count($room)){
									$data['room_id'] = $room['room_id'];
								}else{
									$this->ajaxReturn('不存在该房间', 'json');
								}
								
								//开始保存数据
								$data['createtime'] = time();
								$data['code'] = rand(100000, 999999);
								$data['user_id'] = session('user_id');
								$data['istype'] = 1;
								//关联设备
								$eqmlist = D('Eqment')->getEqmentListByRoomnumber($data['room_number']);
								if(is_array($eqmlist) && count($eqmlist)){
									$newAtt = array();
									foreach($eqmlist as $ls){
										$arr = array(
											'eqment_id' => $ls['id'],
											'eqmnumber' => $ls['eqmnumber'],
											'typeid' => $ls['typeid'],
											'eqmtitle' => $ls['eqmtitle'],
											'room_id' => $ls['room_id'],
											'roomnumber' => $ls['roomnumber'],
											'contract' => $data['contract'],
											'real_start_number' => $ls['last_number'],
											'real_last_number' => $ls['last_number'],
											'old_last_number' => $ls['last_number'],
											'rates' => $ls['rates'],
											'user_id' => session('user_id'),
											'user_nick' => session('nickname'),
											'createtime' => time(),
										);
										
										if($ls['typeid'] == 1){
											$eqment_1 = I('post.eqment_1');
											$ls['last_number'] = $data['eqment_1'] = $ls['last_number']/10;
										}else if($ls['typeid'] == 2){
											$eqment_2 = I('post.eqment_2');
											$ls['last_number'] = $data['eqment_2'] = $ls['last_number']/10;
										}else if($ls['typeid'] == 3){
											$eqment_3 = I('post.eqment_3');
											$ls['last_number'] = $data['eqment_3'] = $ls['last_number']/10;
										}
										
										$newAtt[] = $arr;
									}
								}
								//保存用户数据
								$row = D('Member')->addMemberInfo($data);
								//发送短信验证码
								if($row !== false){
									//关联表信息
									D('EqmentRoom')->addEqmentInfoToRoomAll($newAtt);
									unset($newAtt);
									//$this->sendCode($data['member_phone'], $data['code'], $data['member_nick'], $type, $data['room_number'], $floor, $roomtype, $times);
								}
							}
						}
					}
					//删除文件
					unlink($filename);
					$this->lists();
				}else{
					echo 'Error3';
				}
			}
		}else{
			echo "Error2";
		}
	}

	/**
	 * 发送短信验证码
	 * @param string $phone
	 * @param int $code
	 **/
	private function sendCode($phone, $code, $name='', $type='',$room_number='', $floor=1, $roomtype='', $times='', $istype=0){
		$smsurl = 'http://m.5c.com.cn/api/send/index.php?';
		if($istype){
			$message = "尊敬的嘛嘛公寓". $room_number ."房间". $name ."客人，你好！您的房间费用将于". $times ."到期，请及时缴纳下期费用。管家电话：(023)65157522.";
		}else{
			$message = "【嘛嘛公寓】尊敬的".$room_number."房间 ".$name." 客人，您好！欢迎你入住嘛嘛城市公寓熙街店。您的授权码为：". $code ."。可以前台自助制卡，关注微信公众号<嘛嘛公寓>，可查水电费。公寓管家热线：023-65659672。嘛嘛公寓，有爱的青年创意公寓！";
		}
		
		$param = array(
			'username' => 'mmgy',
			'password_md5' => md5('mamagongyu2015'),
			'apikey' => 'cd983820e908517d1c8b6fb9762a5ae3',
			'mobile' => $phone,
			'content' => urlencode($message),
			'encode' => 'UTF-8'
		);
		
		$paramstring = http_build_query($param);
		$content = file_get_contents($smsurl. $paramstring);
		if(strpos($content, 'success') >= 0){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 获取水电气表初始值
	 **/
	public function ajaxeqm(){
		$room_number = I('get.roomnumber') ? trim(I('get.roomnumber')) : '';
		//获取房间押金
		$roominfo = D('Room')->getRoomInfoByNumber($room_number);
		if(count($roominfo)){
			$data['deposit'] = $roominfo['deposit'];
			$data['rent'] = $roominfo['rent'];
			$data['property'] = $roominfo['property'];
		}else{
			$data['deposit'] = 0;
		}
		
		//关联设备
		$eqmlist = D('Eqment')->getEqmentListByRoomnumber($room_number);
		if(is_array($eqmlist) && count($eqmlist)){
			$data['errCode'] = 1;
			foreach($eqmlist as $ls){
				if($ls['typeid'] == 1){
					$data['eqment_1'] = $ls['last_number']/10;
				}else if($ls['typeid'] == 2){
					$data['eqment_2'] = $ls['last_number']/10;
				}else if($ls['typeid'] == 3){
					$data['eqment_3'] = $ls['last_number']/10;
				}
			}
		}else{
			$data = array(
				'errCode' => 0,
				'eqment_1' => 0,
				'eqment_2' => 0,
				'eqment_3' => 0,
			);
		}

		$this->ajaxReturn($data);
	}

	/**
	 * 获取享受的活动信息
	 **/
	public function ajaxevent(){
		$btime = I('btime', ''); //合同开始时间
		$etime = I('etime', ''); //合同结束时间
		$roomnumber = I('roomnumber', '');
		
		$attrList = array();
		if(empty($btime) || empty($etime)){
			
		}else{
			//获取房间
			$roomInfo = D('Room')->getRoomInfoByNumber($roomnumber);
			if(count($roomInfo)){
				$attrList = D('Eventtype')->getMemberEventTypeByBtime($btime, $etime, $roomInfo['root_type']);
			}else{
				$attrList = D('Eventtype')->getMemberEventTypeByBtime($btime, $etime);
			}
			//返回值
			$this->assign('event', $attrList);
			$html = $this->fetch('Member/eventinfo');
			$this->ajaxReturn($html);
		}
	}

	/**
	 * 合同号管理
	 *
	 **/
	public function contract(){
		if(IS_GET){
			$page = I('get.page') ? (int)I('get.page') : 1;
			$ajax = I('get.ajax') ? (int)I('get.ajax') : 0;
			//获取总数
			$count = D('Member')->getContractCountByWhere($where);
			//获取列表
			$list = D('Member')->getContractListByWhere($where, $page);

			$this->assign('list', $list);
			$this->assign('count', $count);
			$this->assign('page', $page);
			//判断请求方式
			if(!$ajax){
				$this->display('contract');
			}else{
				$this->display('contract_list', 'utf-8', 'html');
			}
		}else{
			$contract = I('post.contract', '');
			$counts = I('post.counts', 1);
			if(empty($contract)){
				$this->ajaxReturn('请输入合同编号');
			}else{
				//合同后半部分
				$lastStr = substr($contract, -3, 3);
				//获取合同长度
				$lens = strlen($contract);
				//获取合同前半部分
				$befromContract = substr($contract, 0, ($lens-3));
				//开始生成合同号
				for($i=1;$i<=$counts;$i++){
					//合同编号
					$newContract = $befromContract . str_pad(($lastStr+$i), 3, '0', STR_PAD_LEFT);
					//判断数据库是否存在
					if(D('Member')->getContractCountByWhere(array('contract' => $newContract))){
						//
					}else{
						$newData[] = array(
							'contract' => $newContract,
							'createtime' => time(),
							'visible' => 1,
							'admin_nick' => session('nickname'),
							'status' => 0
						);
					}
				}
				//开始保存合同
				if(is_array($newData) && count($newData)){
					if(D('Member')->addContractInfo($newData)){
						$this->ajaxReturn('操作成功');
					}else{
						$this->ajaxReturn('操作失败');
					}
				}else{
					$this->ajaxReturn('合同已存在');
				}
			}
		}
	}

	/**
	 * 删除合同
	 **/
	public function contractrem(){
		$contract_id = I('cid', 0);
		$status = I('status', 0);
		
		if(D('Member')->deleteContractInfo($contract_id, $status) !== false){
			echo 1;
		}else{
			echo 0;
		}
	}

	/**
	 * 图片上传
	 **/
	public function upload(){
		if(!empty($_FILES['file']['tmp_name'])){
		    $upload = new \Think\Upload();// 实例化上传类
		    $upload->maxSize   =     3145728 ;// 设置附件上传大小
		    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		    $upload->rootPath  =     './Public/upload/'; // 设置附件上传根目录
		    $upload->savePath  =     ''; // 设置附件上传（子）目录
		    // 上传文件 
		    $info   =   $upload->upload();
		    if(!$info) {// 上传错误提示错误信息
		        $data = array('errCode' => 0, 'errMsg' => $upload->getError());
		    }else{// 上传成功
		        foreach($info as $file){
			        $newImage[] = $file['savepath'].$file['savename'];
			    }
				
				$data = array('errCode' => 1, 'errMsg' => serialize($newImage));
		    }
	    }else{
	    	$data = array('errCode' => 0, 'errMsg' => '请选择上传的图片');
	    }
		
		echo json_encode($data);
	}
	
	/**
	 * 房间费用规则
	 **/
	public function memberchart(){
		/*
		$year = D('Y', time());
		//查询租用率
		$month1 = D('Member')->getMemberListCount(array(
			'visible' => 1,
			'etime' => array('between', array(strtotime($year.'-01-01 00:00:00'), strtotime($year. '-03-31 23:59:59')))
		));

		$month2 = D('Member')->getMemberListCount(array(
			'visible' => 1,
			'etime' => array('between', array(strtotime($year.'-04-01 00:00:00'), strtotime($year. '-06-30 23:59:59')))
		));

		$month3 = D('Member')->getMemberListCount(array(
			'visible' => 1,
			'etime' => array('between', array(strtotime($year.'-07-01 00:00:00'), strtotime($year. '-09-30 23:59:59')))
		));

		$month4 = D('Member')->getMemberListCount(array(
			'visible' => 1,
			'etime' => array('between', array(strtotime($year.'-10-01 00:00:00'), strtotime($year. '-12-31 23:59:59')))
		));
		*/
		//计算总数

		$this->display('chart/memberchart');
	}
	
	/**
	 * 下载合同
	 **/
	public function download(){
		//获取参数
		$userid = I('get.userid', 0);
		if(!$userid){
			exit;
		}
		//获取用户详情
		$list = D('Member')->getMemberListAll(array(
			'member_id' => rtrim($userid, ',')
		));
		if(empty($list)){
			exit;
		}
		//导入三方插件
		import("Org.Util.PHPWord");
		$fileUrl = "contract/1.docx";
		$PHPWord = new \PHPWord();
		$PHPWord_Template = $PHPWord->loadTemplate($fileUrl);
		foreach($list as $info){
			$filename = "";
			//月数
			$month = getMonthNum(date('Y-m-d', $info['btime']), date('Y-m-d', $info['etime']));
			//获取房间默认的价格
			$roomrent = D('Room')->getRoomInfoByNumber($info['room_number']);
			
			if($info['rent'] <= 0){
				$info['rent'] = $roomrent['rent'];
				$info['property'] = $roomrent['property'];
				$info['deposit'] = $roomrent['deposit'];
			}
			
			//加载优惠活动
			$event = D('Eventtype')->getMemberEventTypeByBtime(date('Y-m-d', $info['btime']), date('Y-m-d', $info['etime']), $roomrent['root_type'], $info['contract']);
			//计算优惠的月租
			if(count($event)){
				$eventDiscount = ($info['rent'] * $event['rent_count']) - ($info['rent'] * $event['rent_multiple'] * $event['rent_count']); //优惠的房租
			}else{
				$eventDiscount = 0;
			}
			//计算总体房租
			$rentTotal = $month * $info['rent'] - $eventDiscount;
			$rentTotal = sprintf('%.2f', $rentTotal);
			//获取费率
			$flinfo = M('system')->where(array('id' => 1))->find();
			//设置数据
			$PHPWord_Template->setValue('contract', $info['contract']);
			$PHPWord_Template->setValue('name', iconv('utf-8', 'GBK', $info['member_nick']));
			$PHPWord_Template->setValue('card', $info['member_card']);
			$PHPWord_Template->setValue('phone', $info['member_phone']);
			$PHPWord_Template->setValue('address', iconv('utf-8', 'GBK', $info['address']));
			$PHPWord_Template->setValue('jname', iconv('utf-8', 'GBK',$info['j_name']));
			$PHPWord_Template->setValue('jphone', $info['j_phone']);
			$PHPWord_Template->setValue('room', $info['room_number']);
			$PHPWord_Template->setValue('time', date('Y-m-d', $info['btime']));
			$PHPWord_Template->setValue('btime', date('Y-m-d', $info['btime']));
			$PHPWord_Template->setValue('etime', date('Y-m-d', $info['etime']));
			$PHPWord_Template->setValue('count', $month); //多少月
			$PHPWord_Template->setValue('total', iconv('utf-8', 'GBK', '￥'. $rentTotal)); //总额
			$PHPWord_Template->setValue('rent', iconv('utf-8', 'GBK', '￥'.$info['rent']));
			$PHPWord_Template->setValue('brent', iconv('utf-8', 'GBK', $this->cny($info['rent'])));
			$PHPWord_Template->setValue('bcount', 1);
			$PHPWord_Template->setValue('bzrent', iconv('utf-8', 'GBK', '￥'.$info['deposit'])); //保证金 GB2312//IGNORE
			$PHPWord_Template->setValue('paytt', 1);
			$PHPWord_Template->setValue('bbzrent', iconv('utf-8', 'GBK', $this->cny($info['deposit']))); //保证金大写
			$PHPWord_Template->setValue('property', iconv('utf-8', 'GBK', '￥'.$info['property']));
			$PHPWord_Template->setValue('eletric', iconv('utf-8', 'GBK', '￥'.$flinfo['electric']));
			$PHPWord_Template->setValue('water', iconv('utf-8', 'GBK', '￥'.$flinfo['water']));
			$PHPWord_Template->setValue('elecount', iconv('utf-8', 'GBK', $info['eqment_2']));
			$PHPWord_Template->setValue('watercount', iconv('utf-8', 'GBK', $info['eqment_1']));
			$PHPWord_Template->setValue('desc', iconv('utf-8', 'GBK', $event['remark'])); //优惠活动
			//设置目录
			$dir = 'contract/'. date('Y-m-d', $info['btime']);
			//创建目录
			$res = !is_dir($dir) ? mkdir($dir, 0777, true) : true;
			if($res){
				//文件地址
				$filename = $dir.'/'. $info['contract'] .'.docx';
				$PHPWord_Template->save($filename);
				
				//下载文件
				$fileinfo = pathinfo($filename);
				header('Content-type: application/x-'.$fileinfo['extension']);
				header('Content-Disposition: attachment; filename='.$fileinfo['basename']);
				header('Content-Length: '.filesize($filename));
				readfile($filename);
			}
		}
	}
	
	/**
	 * 数字现金转中文大写
	 *
	 **/
	private function _cny_map_unit($list,$units) { 
	    $ul = count($units); 
	    $xs = array(); 
	    foreach (array_reverse($list) as $x) { 
	        $l = count($xs); 
	        if ($x!="0" || !($l%4)){
				$n = ($x=='0'?'':$x).($units[($l-1)%$ul]); 
	        }else{
				$n = is_numeric($xs[0][0]) ? $x : '';
			}
			
	        array_unshift($xs,$n); 
	    } 
		
	    return $xs; 
	}

	private function cny($ns) { 
	    static 	$cnums = array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"), 
	        	$cnyunits = array("圆","角","分"), 
	        	$grees = array("拾","佰","仟","万","拾","佰","仟","亿"); 
	    list($ns1,$ns2) = explode(".",$ns,2); 
	    $ns2 = array_filter(array($ns2[1],$ns2[0])); 
	    $ret = array_merge($ns2,array(implode("", $this->_cny_map_unit(str_split($ns1),$grees)),"")); 
	    $ret = implode("",array_reverse($this->_cny_map_unit($ret,$cnyunits))); 
	    $string = str_replace(array_keys($cnums),$cnums,$ret);
		//整数后面添加"整"
		return $string;
	}
	
	/**
	 * 字体转化
	 **/
	private function iconvs($str){
		//判断是否存在繁体 true是 false 否
		$flag = iconv('GB2312//IGNORE', 'UTF-8', $str) === false ? true : false;
		//如果存在，先转换成简体
		if($flag){
			echo '--- 存在繁体 ---';
			$str = iconv('GB2312', 'GBK', $str);
		}
		
		return iconv('GB2312', 'UTF-8', $str);
	}
	
	//查询图片
	public function thumb(){
		$member_id = I('get.mid', 784);
		$info = D('Member')->getMemberInfoById($member_id, 0);
		
		if(is_array($info) && count($info)){
			$images = html_entity_decode($info['images']);
			$list = unserialize($images);
			$this->assign('list', $list);
			$this->display();
		}else{
			exit;
		}
	}
	
	/**
	 * 制卡操作
	 **/
	public function ajax(){
		$userid = I('get.userid', 0);
		//用户信息
		$info = D('Member')->getMemberInfoById($userid);
		if(is_array($info) && count($info)){
			$sdata = array();
			$sdata['roomnumber'] = $info['room_number'];
			
			if($info['leaving_time'] < time()){
				//判断是否在48小时之内，并且是长租客人 istype == 1
				if($info['istype'] == 1 && $this->diffBetweenTwoDays($info['leaving_time'], time()) <= 2){
					$msg = "您的卡已失效，请购买临时卡（收取卡押金￥100.00）制卡，有效开门时间24小时。请及时到公寓管家处办理续费和退卡手续。";
					//判断是否存在制卡记录
					$infos = D('Roomcard')->getRoomCardInfoByWhere(array(
						'member_id' => $info['member_id'],
						'is_back' => 0
					));
					//设置参数
					$sdata['btime'] = $info['begintime'] = date('ymdHi', time());
					//判断时间
					if(is_array($infos) && count($infos)){
						$sdata['etime'] = date('ymdHi', $infos['leav_time']);
						$endstime = date('Y-m-d H:i', $infos['leav_time']);
					}else{
						$sdata['etime'] = date('ymdHi', (time() + 86400));
						$endstime = date('Y-m-d H:i', (time() + 86400));
					}
					//设置锁号
					$sdata['locknum'] = str_pad($info['room_number'], 6, '01', STR_PAD_LEFT).'99';
					$info['iscq'] = 1;
					$sdata['uid'] = session('user_id');
					
					$this->ajaxReturn(array(
						'errCode' => 1,
						'errMsg' => $msg,
						'info' => $sdata,
						'times' => date('Y-m-d H:i', time()) . ' ~ ' . $endstime
					));
				}else{
					$this->ajaxReturn(array(
						'errCode' => 0,
						'errMsg' => '您的租期已失效'
					));
				}
			}else{
				//设置参数
				if($info['checkin_time'] >= time()){
					$btime = $info['checkin_time'];
				}else{
					$btime = time();
				}
				
				//判断结束时间是否是大于1个月
				$month = $this->getMonthNum(date('Y-m-d', $info['leaving_time']), date('Y-m-d', time()));
				$month = $month < 1 ? 1 : $month;
				if($month > 1){
					$etime = strtotime("+1 month");
				}else{
					$etime = $info['leaving_time'];
				}
				
				//设置锁号
				$sdata['locknum'] = str_pad($info['room_number'], 6, '01', STR_PAD_LEFT).'99';
				
				$msg = "尊敬的 ". $info['room_number'] ." 房间 ". $info['member_nick'] ." 客人，您好！<br />
				您的房租有效期是：". date('Y-m-d H:i', $btime)."~". date('Y-m-d H:i', $etime) ."<br />
				";
				//格式化时间
				$sdata['btime'] = $info['begintime'] = date('ymdHi', $btime);
				$sdata['etime'] = date('ymdHi', $etime);
				$info['iscq'] = 0;
				$sdata['uid'] = session('user_id');
				$this->ajaxReturn(array(
					'errCode' => 1,
					'errMsg' => $msg,
					'info' => $sdata,
					'times' => date('Y-m-d H:i', $btime) . ' ~ ' . date('Y-m-d H:i', $etime)
				));
			}
		}
	}
	
	/**
	 * 保存制卡数据
	 **/
	public function ajaxcard(){
		$data['card'] = I('get.card') ? trim(I('get.card')) : '';
		$data['card_udid'] = $data['card'];
		$data['lock_id'] = I('get.lock_id') ? trim(I('get.lock_id')) : '';
		$data['member_id'] = I('get.uid') ? (int)I('get.uid') : 0;
		$data['card_type'] = I('get.iscq') ? (int)I('get.iscq') : 6;
		$data['createtime'] = time();
		//获取用户详情
		$userinfo = D('Member')->getMemberInfoById($data['member_id']);
		//判断是否存在用户信息
		if(is_array($userinfo) && count($userinfo)){
			if($userinfo['leaving_time'] < time()){
				//判断是否在48小时之内，并且是长租客人 istype == 1
				if($userinfo['istype'] == 1 && $this->diffBetweenTwoDays($userinfo['leaving_time'], time()) <= 2){
					//设置参数
					$data['checkin_time'] = time();
					//判断是否存在制卡记录
					$infos = D('Roomcard')->getRoomCardInfoByWhere(array(
						'card_udid' => $data['card_udid'],
						'member_id' => $data['member_id'],
						'is_back' => 0
					));
					
					if(is_array($infos) && count($infos)){
						if(D('Roomcard')->editRoomCardInfoByLogIds(array('createtime' => time()), $infos['id']) !== false){
							$this->ajaxReturn(array(
								'errCode' => 1,
								'errMsg' => 'Success.',
							));
						}else{
							$this->ajaxReturn(array(
								'errCode' => 0,
								'errMsg' => 'Fail!',
							));
						}
					}else{
						$data['leav_time'] = time() + 86400; //延长一天
						$data['room_number'] = $userinfo['room_number'];
						$data['m_nickname'] = $userinfo['member_nick'];
						
						$row = D('Roomcard')->addRoomCardnfo($data);
						if($row){
							$this->ajaxReturn(array(
								'errCode' => 1,
								'errMsg' => 'Success.',
							));
						}
					}
				}
			}else{
				//设置参数
				if($userinfo['checkin_time'] >= time()){
					$data['checkin_time'] = $userinfo['checkin_time'];
				}else{
					$data['checkin_time'] = time();
				}
				//判断是否存在制卡记录
				$infos = D('Roomcard')->getRoomCardInfoByWhere(array(
					'card_udid' => $data['card_udid'],
					'member_id' => $data['member_id'],
					'is_back' => 0
				));
				
				if(is_array($infos) && count($infos)){
					if(D('Roomcard')->editRoomCardInfoByLogIds(array('createtime' => time()), $infos['id']) !== false){
						$this->ajaxReturn(array(
							'errCode' => 1,
							'errMsg' => 'Success.',
						));
					}else{
						$this->ajaxReturn(array(
							'errCode' => 0,
							'errMsg' => 'Fail!',
						));
					}
				}else{
					//判断结束时间是否是大于1个月
					$month = $this->getMonthNum(date('Y-m-d', $userinfo['leaving_time']), date('Y-m-d', time()));
					if($month > 1){
						$data['leav_time'] = strtotime("+1 month");
					}else{
						$data['leav_time'] = $userinfo['leaving_time'];
					}
				}
				$data['room_number'] = $userinfo['room_number'];
				$data['m_nickname'] = $userinfo['member_nick'];
				
				$row = D('Roomcard')->addRoomCardnfo($data);
				if($row){
					$this->ajaxReturn(array(
						'errCode' => 1,
						'errMsg' => 'Success.',
					));
				}
			}
		}else{
			$this->ajaxReturn(array(
				'errCode' => 0,
				'errMsg' => 'Fail!',
			));
		}
	}
	
	private function getMonthNum( $date1, $date2, $tags='-' ){
	 	$date1 = explode($tags,$date1);
	 	$date2 = explode($tags,$date2);
	 	return abs($date1[0] - $date2[0]) * 12 + abs($date1[1] - $date2[1]);
	}

	private function diffBetweenTwoDays ($second1, $second2){
  		if ($second1 < $second2) {
   			$tmp = $second2;
    		$second2 = $second1;
    		$second1 = $tmp;
  		}

  		return ($second1 - $second2) / 86400;
	}
}


   